#include "product.h"
#include "ui_product.h"

product::product(QWidget *parent) :
    QMainWindow(parent),
    //db(nullptr),
     currentPage(0),
     m_payment(new payment(this)),
    ui(new Ui::product)
{
    ui->setupUi(this);

    // 设置数据库连接（这里以QSQLITE为例）
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("./../server/product.db"); // 替换为你的数据库文件名

        // 打开数据库连接
        if (!db.open()) {
            qDebug() << "Failed to open database:" << db.lastError();
            //return -1;
        }

        // 从数据库中读取数据
         dataList = readDataFromDatabase(db);

        // 打印读取的数据
        for (const QVariantMap &row : dataList) {
            qDebug() << "ID:" << row["id"].toInt()
                     << "Name:" << row["name"].toString()
                     << "price:" << row["price"].toInt();
        }

//---------------------------------------------------------
    QDir dir("/mnt/hgfs/aic_jeff/QT/项目文件夹/自动售卖机/client/image_product");
            QStringList filters;
            filters << "*.png" << "*.jpg" << "*.jpeg" << "*.bmp";
            dir.setNameFilters(filters);
            imagePaths = dir.entryList(QDir::Files);

            int totalImages = imagePaths.size();
            int pages = (totalImages + 8) / 9; // 向上取整

            stackedWidget = new QStackedWidget(this);


            for (int i = 0; i < pages; ++i)
                        {
                            QWidget *page = new QWidget();
                            QGridLayout *gridLayout = new QGridLayout(page);

                            int row = 0;
                            int col = 0;
                            for (int j = i * 9; j < (i + 1) * 9 && j < totalImages; ++j) {
                                QString imageName = imagePaths[j];
                                QString imagePath = dir.absoluteFilePath(imageName);
                                pixmap=QPixmap(imagePath);
                                if (pixmap.isNull()) {
                                    continue;
                                }

                                QPushButton *button = new QPushButton(page);
                                button->setIcon(QIcon(pixmap.scaled(QSize(100, 100), Qt::KeepAspectRatio, Qt::SmoothTransformation)));
                                button->setIconSize(QSize(100, 100));
                                button->setText("");
                                button->setFlat(true);
                                // 使用lambda表达式传递图片路径到槽函数中
                                connect(button, &QPushButton::clicked, this, [this, imagePath,row,col,j](){

                                   // payment *m_payment = new payment(this);
                                    QPixmap payment_pixmap(imagePath);//重新加载图片，不能用原来的pixmap
                                     QPixmap scaledPixmap = payment_pixmap.scaled(m_payment->ui->product_image->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);

                                   m_payment->ui->product_image->setPixmap(scaledPixmap);
                                   //----------------------------------------------------------
                                    int offset=row*3+col;
                                        QVariantMap rowData = dataList[offset];
                                       // 现在你可以访问rowData中的任何字段了
                                        /*
                                       qDebug() << "ID:" << rowData["id"].toInt();
                                       qDebug() << "Name:" << rowData["name"].toString();
                                       qDebug() << "price:" << rowData["price"].toString();
                                       */
                                        int num_label=1+j;
                                       m_payment->ui->product_name->setText(rowData["name"].toString());
                                       m_payment->ui->product_num->setText(QString::number(num_label));
                                       m_payment->ui->product_price->setText(rowData["price"].toString());
                                   //-------------------------------------------------
                                    m_payment->show();
                                });

                                gridLayout->addWidget(button, row, col);

                                col++;
                                    if (col >= 3)
                                    {
                                        col = 0;
                                        row++;
                                    }
                            }

                            stackedWidget->addWidget(page);
                        }
            QWidget *centralWidget = new QWidget(this);
            QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
            setCentralWidget(centralWidget); // 将 centralWidget 设置为 QMainWindow 的中心部件

            mainLayout->addWidget(stackedWidget);

            if (pages > 1) {
                QHBoxLayout *buttonLayout = new QHBoxLayout();
                QPushButton *prevButton = new QPushButton("Previous", this);
                prevButton->setObjectName("prevButton"); // 设置 objectName
                QPushButton *nextButton = new QPushButton("Next", this);
                nextButton->setObjectName("nextButton"); // 设置 objectName
                prevButton->setEnabled(false); // 第一页时禁用“Previous”按钮

                connect(prevButton, &QPushButton::clicked, this, &product::onPrevButtonClicked);
                connect(nextButton, &QPushButton::clicked, this, &product::onNextButtonClicked);

                buttonLayout->addWidget(prevButton);
                buttonLayout->addWidget(nextButton);
                buttonLayout->addStretch(); // 添加弹性空间

                mainLayout->addLayout(buttonLayout);

                // 保存按钮的指针，以便后续使用
                prevButtonPtr = prevButton;
                nextButtonPtr = nextButton;
            }

            setWindowTitle("Image Player");
        }

        void product::onPrevButtonClicked() {
            if (currentPage > 0) {
                --currentPage;
                stackedWidget->setCurrentIndex(currentPage);
                updateButtonStates();
            }
        }

        void product::onNextButtonClicked() {
            int totalPages = stackedWidget->count();
            if (currentPage < totalPages - 1) {
                ++currentPage;
                stackedWidget->setCurrentIndex(currentPage);
                updateButtonStates();
            }
        }

        void product::updateButtonStates() {
            if (currentPage == 0) {
                prevButtonPtr->setEnabled(false);
                nextButtonPtr->setEnabled(true);
            } else if (currentPage == stackedWidget->count() - 1) {
                prevButtonPtr->setEnabled(true);
                nextButtonPtr->setEnabled(false);
            } else {
                prevButtonPtr->setEnabled(true);
                nextButtonPtr->setEnabled(true);
            }
        }

product::~product()
{
    delete ui;
}

// 函数：从数据库中读取数据并存储在QList<QVariantMap>中
QList<QVariantMap> product::readDataFromDatabase(QSqlDatabase &db) {
    QList<QVariantMap> resultList;

    // 创建查询对象
    QSqlQuery query(db);

    // 执行SQL查询
    QString sql = "SELECT id, name, price FROM product"; // 替换为你的表名
    if (!query.exec(sql)) {
        qDebug() << "Failed to execute query:" << query.lastError();
        return resultList; // 如果查询失败，返回空列表
    }

    // 遍历查询结果
    while (query.next()) {
        QVariantMap rowData;
        rowData["id"] = query.value(0); // 第一列是id
        rowData["name"] = query.value(1); // 第二列是name
        rowData["price"] = query.value(2); // 第三列是value
        resultList.append(rowData);
    }

    return resultList;
}
